import React, { useEffect, useCallback, useMemo, useState } from 'react'
import { useParams } from 'react-router-dom'
import { Typography, Card, message, Input, Tag, Space, Button, Drawer } from 'antd'
import { FireOutlined, BulbOutlined } from '@ant-design/icons'
import { TipTapEditor } from '../../components/Editor/RichTextEditor'
import { DocumentStateProvider, useDocumentState, SparkCreationProvider } from '../../state'
import { useAutoSave, SaveStatus } from '../../hooks/useAutoSave'
import SaveIndicator from '../../components/SaveIndicator'
import { getAIConfig } from '../../../services/ai'
import { AIService } from '../../../services/ai/aiService'
import { SparkCreationPanel } from '../../components/SparkCreation'
import { TitleSuggestionModal } from '../../components/TitleSuggestion'
import { htmlToMarkdown } from '../../utils/exportUtils'

const { Title, Paragraph } = Typography

const TextEditorContent: React.FC = () => {
  const { id } = useParams<{ id?: string }>()
  const { state, actions } = useDocumentState()
  const [isSparkDrawerOpen, setIsSparkDrawerOpen] = useState(false)
  const [isTitleSuggestionModalOpen, setIsTitleSuggestionModalOpen] = useState(false)

  // AI服务实例
  const aiService = useMemo(() => {
    const config = getAIConfig()
    if (!config || !config.apiKey) {
      return null
    }
    return new AIService({
      openaiApiKey: config.apiKey,
      baseURL: config.apiBaseUrl || undefined,
      model: config.model || 'gpt-3.5-turbo'
    })
  }, [])

  // 配置自动保存
  const autoSave = useAutoSave(
    state.draftContent,
    async () => {
      // 调用状态管理的保存函数
      await actions.saveDocument()

      // 发送文档保存事件，通知列表页刷新
      window.dispatchEvent(
        new CustomEvent('document:saved', {
          detail: { id: state.currentDocument?.id }
        })
      )
    },
    {
      delay: 3000, // 3秒后自动保存
      maxRetries: 3, // 最多重试3次
      enabled: true // 启用自动保存
    }
  )

  useEffect(() => {
    const loadOrCreateDocument = async () => {
      if (id) {
        console.log('[TextEditor] 加载文档', id)
        try {
          await actions.loadDocument(id)
        } catch (err) {
          console.error('[TextEditor] 加载文档失败', err)
          message.error('加载文档失败')
        }
      } else {
        console.log('[TextEditor] 创建新文档')
        try {
          await actions.createNewDocument('')
        } catch (err) {
          console.error('[TextEditor] 创建文档失败', err)
        }
      }
    }

    loadOrCreateDocument()
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [id]) // 只依赖 id,不依赖 actions

  const handleContentChange = useCallback(
    (value: string) => {
      actions.updateDraft(value)
    },
    // eslint-disable-next-line react-hooks/exhaustive-deps
    [] // actions.updateDraft 现在是稳定的,不需要作为依赖
  )

  // 处理Spark生成的内容
  const handleSparkContentGenerated = useCallback(
    (content: string) => {
      // 如果当前有内容，询问是否替换
      if (state.draftContent.trim() && content.trim()) {
        message.info('Spark内容已生成，将追加到当前文档')
        const newContent = state.draftContent + '\n\n' + content
        actions.updateDraft(newContent)
      } else {
        // 直接设置内容
        actions.updateDraft(content)
      }

      // 关闭Spark面板
      setIsSparkDrawerOpen(false)
      message.success('Spark创作内容已导入编辑器')
    },
    [state.draftContent, actions]
  )

  // 处理Spark生成的标题
  const handleSparkTitleGenerated = useCallback(
    (title: string) => {
      console.log('[TextEditor] Spark生成标题:', title)
      // 更新文档标题
      actions.updateTitle(title)
    },
    [actions]
  )

  // 打开Spark创作面板
  const handleOpenSparkPanel = useCallback(() => {
    setIsSparkDrawerOpen(true)
  }, [])

  // 关闭Spark创作面板
  const handleCloseSparkPanel = useCallback(() => {
    setIsSparkDrawerOpen(false)
  }, [])

  // 打开智能标题Modal
  const handleOpenTitleSuggestion = useCallback(() => {
    if (!aiService) {
      message.warning('AI服务未配置，请先在设置中配置AI服务')
      return
    }

    if (!state.draftContent.trim()) {
      message.warning('请先输入文章内容')
      return
    }

    setIsTitleSuggestionModalOpen(true)
  }, [aiService, state.draftContent])

  // 关闭智能标题Modal
  const handleCloseTitleSuggestion = useCallback(() => {
    setIsTitleSuggestionModalOpen(false)
  }, [])

  // 生成标题建议
  const handleGenerateTitleSuggestions = useCallback(async (): Promise<string[]> => {
    if (!aiService) {
      throw new Error('AI服务未配置')
    }

    // 将HTML内容转换为Markdown
    const markdownContent = htmlToMarkdown(state.draftContent)

    console.log('[TextEditor] 生成标题建议，内容长度:', markdownContent.length)

    const result = await aiService.generateTitleSuggestions({
      content: markdownContent,
      count: 5
    })

    if (!result.ok) {
      throw new Error(result.error?.message || '生成标题失败')
    }

    return result.data
  }, [aiService, state.draftContent])

  // 选择标题
  const handleSelectTitle = useCallback((title: string) => {
    console.log('[TextEditor] 选择标题:', title)
    actions.updateTitle(title)
    message.success('标题已更新')
  }, [actions])

  const handleTitleChange = useCallback(
    (e: React.ChangeEvent<HTMLInputElement>) => {
      actions.updateTitle(e.target.value)
    },
    // eslint-disable-next-line react-hooks/exhaustive-deps
    [] // actions.updateTitle 现在是稳定的
  )

  // 获取AI配置信息用于显示
  const aiConfig = useMemo(() => getAIConfig(), [])

  // 保存文档处理函数
  const handleSave = useCallback(async () => {
    try {
      await autoSave.saveNow()
      message.success('文档已保存')
    } catch (err) {
      message.error('保存失败')
    }
  }, [autoSave])

  // 快捷键监听
  useEffect(() => {
    const handleKeyDown = (e: KeyboardEvent) => {
      // Ctrl+S 或 Cmd+S 保存
      if ((e.ctrlKey || e.metaKey) && e.key === 's') {
        e.preventDefault()
        handleSave()
      }
    }

    window.addEventListener('keydown', handleKeyDown)
    return () => window.removeEventListener('keydown', handleKeyDown)
  }, [handleSave])

  useEffect(() => {
    if (!state.error) {
      return
    }

    message.error(state.error.message)
    actions.resetError()
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [state.error]) // actions 现在是稳定的

  // 监听页面卸载（刷新或关闭标签页）
  useEffect(() => {
    const handleBeforeUnload = (e: BeforeUnloadEvent) => {
      if (autoSave.status === SaveStatus.UNSAVED || autoSave.status === SaveStatus.SAVING) {
        e.preventDefault()
        e.returnValue = '你有未保存的更改，确定要离开吗？'
        return e.returnValue
      }
    }

    window.addEventListener('beforeunload', handleBeforeUnload)
    return () => window.removeEventListener('beforeunload', handleBeforeUnload)
  }, [autoSave.status])

  return (
    <div style={{ padding: '24px', height: '100%', display: 'flex', flexDirection: 'column' }}>
      {/* 页面标题和AI信息 */}
      <div style={{ marginBottom: '16px', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
        <div>
          <Title level={2} style={{ margin: 0 }}>文本稿件创建</Title>
          <Paragraph type="secondary" style={{ margin: '4px 0 0 0' }}>
            基于AI的智能写作平台,支持Markdown编辑、内容优化和知识库检索
          </Paragraph>
        </div>

        {/* AI配置信息和Spark按钮 */}
        <Space size="middle">
          {aiConfig && (
            <>
              <Tag color="success">已配置</Tag>
              <span style={{ color: '#8c8c8c' }}>
                服务商: <strong>
                  {aiConfig.apiBaseUrl?.includes('siliconflow')
                    ? '硅基流动'
                    : aiConfig.apiBaseUrl?.includes('openai')
                    ? 'OpenAI'
                    : '自定义'}
                </strong>
              </span>
              <span style={{ color: '#8c8c8c' }}>
                模型: <strong>{aiConfig.model || 'gpt-3.5-turbo'}</strong>
              </span>
            </>
          )}

          {/* 智能标题按钮 */}
          <Button
            icon={<BulbOutlined />}
            onClick={handleOpenTitleSuggestion}
            disabled={!aiService || !state.draftContent.trim()}
          >
            智能标题
          </Button>

          {/* Spark创作按钮 */}
          <Button
            type="primary"
            icon={<FireOutlined />}
            onClick={handleOpenSparkPanel}
            style={{
              background: 'linear-gradient(45deg, #ff6b35, #f7931e)',
              border: 'none',
              borderRadius: '6px'
            }}
          >
            火花创作
          </Button>
        </Space>
      </div>

      {/* 编辑器区域 - 全宽 */}
      <Card
        title="编辑器"
        variant="borderless"
        style={{ flex: 1, display: 'flex', flexDirection: 'column' }}
        bodyStyle={{ padding: 0, flex: 1, display: 'flex', flexDirection: 'column' }}
        extra={
          <SaveIndicator
            status={autoSave.status}
            lastSavedAt={autoSave.lastSavedAt}
            onSaveNow={autoSave.saveNow}
          />
        }
      >
        {/* 文档标题输入框 */}
        <div style={{ padding: '12px 16px', borderBottom: '1px solid #f0f0f0', backgroundColor: '#fafafa' }}>
          <Input
            placeholder="请输入文档标题"
            value={state.currentDocument?.title || ''}
            onChange={handleTitleChange}
            size="large"
            style={{
              fontSize: '18px',
              fontWeight: 500,
              backgroundColor: 'transparent'
            }}
            variant="borderless"
          />
        </div>

        {/* TipTap富文本编辑器 */}
        <div style={{ flex: 1, minHeight: 0, overflow: 'auto' }}>
          <TipTapEditor
            content={state.draftContent}
            onChange={handleContentChange}
            theme={state.theme}
            readOnly={false}
            onSave={handleSave}
            documentTitle={state.currentDocument?.title}
          />
        </div>
      </Card>

      {/* Spark创作抽屉 */}
      <Drawer
        title="一键火花创作"
        placement="right"
        size="large"
        open={isSparkDrawerOpen}
        onClose={handleCloseSparkPanel}
        width={800}
        bodyStyle={{ padding: '16px' }}
        destroyOnClose={true}
      >
        <SparkCreationProvider
          onContentGenerated={handleSparkContentGenerated}
          onTitleGenerated={handleSparkTitleGenerated}
        >
          <SparkCreationPanel
            onArticleGenerated={handleSparkContentGenerated}
          />
        </SparkCreationProvider>
      </Drawer>

      {/* 智能标题弹窗 */}
      <TitleSuggestionModal
        visible={isTitleSuggestionModalOpen}
        onClose={handleCloseTitleSuggestion}
        onSelect={handleSelectTitle}
        onGenerate={handleGenerateTitleSuggestions}
      />
    </div>
  )
}

const TextEditorPage: React.FC = () => {
  return (
    <DocumentStateProvider>
      <TextEditorContent />
    </DocumentStateProvider>
  )
}

export default TextEditorPage
